package idao.engine;

import idao.ConnectionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

class JdkDaoProxy extends DaoProxy implements DaoProxyBuilder
{
    @Override
    public <T> T newDaoProxy(Class<T> dao, ConnectionManager cm)
    {
        ClassLoader cl = dao.getClassLoader();
        Class<?>[] interfaces = new Class[] {dao};
        try {
            return dao.cast(Proxy.newProxyInstance(cl, interfaces, new DaoMethodHandler(cm)));
        } catch (Exception e) {
            throw transfromException(e, dao);
        }
    }

    private class DaoMethodHandler implements InvocationHandler
    {
        private ConnectionManager cm;

        DaoMethodHandler(ConnectionManager cm)
        {
            this.cm = cm;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
        {
            return invokeMethod(method, args, cm);
        }
    }
}
